import {Upload, message} from 'antd'
import React, {useState, useEffect} from 'react'
import {LoadingOutlined} from '@ant-design/icons'


// 上传图片组件
const UploadImg = (props) => {

  const {introduction = '', name = '', onChange, fileList1, modifytype} = props
  const [fileList, setfileList] = useState()
  const [formData, setFormState] = useState({loading: false})
  const {loading, imageUrl} = formData

  // 新增二级列表模态框默认值
  useEffect(() => {
    // console.log(modifytype)
    if (modifytype === 1) {
      setfileList([
        {
          uid: '-1',
          name: 'image.png',
          status: 'done',
          url: fileList1,
        },
      ])
    }
  }, [])

  // 上传图片
  const handleChange = info => {
    if (info.file.status === 'uploading') {
      setFormState({loading: true})
      return
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      onChange(info.file.response.url)
      getBase64(info.file.originFileObj, imageUrl =>
        setFormState({
          imageUrl,
          loading: false,
        }),
      )
    }
  }

  // 转换成Base64
  const getBase64 = (img, callback) => {
    const reader = new FileReader()
    reader.addEventListener('load', () => callback(reader.result))
    reader.readAsDataURL(img)
  }

  // 上传图片之前
  const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!')
      return false
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!')
      return false
    }
    return Promise.resolve(file)
  }


  return (
    <>
      <p >{introduction}</p>
      <Upload
        name={name}
        listType="picture-card"
        className="avatar-uploader"
        action="/huangyi/uploadImg"
        beforeUpload={beforeUpload}
        onChange={handleChange}
        fileList={fileList}
      >
        <div>{loading ? <LoadingOutlined /> : '+'}</div>
      </Upload>
    </>
  )
}

export default UploadImg